package com.qqcy.authservice.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * DATE: 2022/1/11
 * Author: huhuan
 * jwt工具类，用于生成token
 */
@Component
public class JwtUtil {

    /**
     * 生成jwt
     *
     * @param userId
     * @return
     */
    public String createJwt(String userId) {
        //获取SECRET_KEY
        PropertiesUtil pro = new PropertiesUtil("token.properties");
        String SECRET_KEY = pro.getPropertyValue("SECRET_KEY");
        String TOKEN_EXPIRE_TIME = pro.getPropertyValue("TOKEN_EXPIRE_TIME");
        System.out.println(SECRET_KEY);
        System.out.println(TOKEN_EXPIRE_TIME);

        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);

        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");

        //生成token：头部+载荷+签名，这里设置过期时间有点问题，暂时不设置，使用默认的过期时间
        return JWT.create().withHeader(header)
                .withClaim("userId",userId)
                .sign(algorithm);
    }

    public Map<String, Claim> parseJwt(String token){
        Map<String,Claim> claims = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256(token);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            claims = jwt.getClaims();
            return claims;
        } catch (Exception e) {
            return null;
        }
    }
}
